from io import BytesIO
import threading
from tkinter import Image
import uuid
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import fitz
from dingtalk_service.yida_client_base import YidaClientBase
from reportservice.helpers import ApiResponse
from reportlab.lib.utils import ImageReader
import json
import requests
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from PyPDF2 import PdfWriter, PdfReader
from oss_service.views import bucket
from io import BytesIO
from datetime import datetime
from yida_app_service.utils.xmutils import xm_fake_sign
from yida_app_service.views import get_xm_client, get_yida_client
from yida_app_service.xu_cloud_client import XmCloudBaseClient


@csrf_exempt
@require_http_methods(["GET"])
def get_detection_model_list(request,company_name):
    model_name = request.GET.get('q')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.get_detection_model_selection_list(name=model_name)
    if result.get("code") == 200:
        success_res = [
                {
                    "text":item["label"],
                    "value":str(item["value"])
                } for item in result.get("data")
            ]
        return ApiResponse.success(data=success_res)

@csrf_exempt
@require_http_methods(["GET"])
def get_xm_qualification_options(request,company_name):
    '''获取资质列表'''
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()  
    result = xm_client.get_qualification_selection_list()
    if result.get("code") == 200:
        success_res = [
                {
                    "text":item["label"],
                    "value":str(item["value"])
                } for item in result.get("data")
            ]
        return ApiResponse.success(data=success_res)

@csrf_exempt
@require_http_methods(["GET"])
def get_xm_exam_category(request,company_name):
    qualification_id = request.GET.get('qualification_id')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()    
    result = xm_client.get_exam_category_selection_list(qualification_id=qualification_id)
    if result.get("code") == 200:
        success_res = [
                {
                    "text":item["label"],
                    "value":str(item["value"])
                } for item in result.get("data")
            ]
        return ApiResponse.success(data=success_res)
    

@csrf_exempt
@require_http_methods(["GET"])
def get_xm_exam_item_detail(request,company_name):
    id = request.GET.get('id')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.get_xm_exam_item_detail(id)    
    if result.get("code") == 200:
        return ApiResponse.success(data=result.get("data"))
@csrf_exempt
@require_http_methods(["GET"])
def get_xm_exam_items(request,company_name):
    category_id = request.GET.get('category_id')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()    
    result = xm_client.get_exam_item_selection_list(exam_category_id=category_id)
    if result.get("code") == 200:
        success_res = [
                {
                    "text":item["label"],
                    "value":str(item["value"])
                } for item in result.get("data")
            ]
        return ApiResponse.success(data=success_res)

@csrf_exempt
@require_http_methods(["GET"])
def get_xm_exam_params(request,company_name):
    project_id = request.GET.get('project_id')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()    
    result = xm_client.get_exam_params_list(project_id=project_id)
    if result.get("code") == 200:
        return ApiResponse.success(data=result.get("data").get("data"))
    

@csrf_exempt
@require_http_methods(["POST"])
def sign_name_to_full_report(request,company_name):
    req_data = json.loads(request.body)
    form_uuid = req_data.get('form_uuid')
    attachement_component_id = req_data.get('attachement_component_id')
    form_inst_id = req_data.get('form_inst_id')
    model_id = req_data.get('model_id')
    sign_config:list = req_data.get('sign_conifg')
    YidaClient = get_yida_client(company_name)
    yida_client:YidaClientBase = YidaClient()
    yida_res = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,yida_client.admin_user_id)
    form_data = yida_res[0].form_data
    pdf_attachement = form_data.get(attachement_component_id)
    if not pdf_attachement:
        return ApiResponse.fail("未找到附件")
    atta = json.loads(pdf_attachement)[0]
    pdf_url = atta.get("downloadUrl")
    if not (pdf_url.startswith("https://api.zjxmyq.cn") or pdf_url.startswith("https://doc.zjxmyq.cn") or pdf_url.startswith("https://api.zjcxjc.cn") or pdf_url.startswith("https://doc.zjcxjc.cn")):
        res = yida_client.get_full_download_url(yida_client.admin_user_id,pdf_url)
        pdf_url = res.body.result
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()  
    result = xm_client.get_model_info(model_id=model_id)  
    if result.get("code") == 200:
        model_info = result.get("data")
        sign_area = model_info.get("sign_area")
        if sign_area:
            response = requests.get(pdf_url)
            if response.status_code == 200:
                pdf_content = BytesIO(response.content)
                pdf_reader = PdfReader(pdf_content)
                pdf_writer = PdfWriter()
                for page_number in range(len(pdf_reader.pages)):
                    current_page = pdf_reader.pages[page_number]
                    for sign in sign_config:
                        sign_positions = [item for item in sign_area if item["name"] == sign.get("name") and item["page"] == page_number + 1]
                        seal_id = sign.get("seal_id")
                        seal_url = form_data.get(seal_id)
                        seal_file_res = requests.get(seal_url)
                        if seal_file_res.status_code == 200:
                            seal_file_content = seal_file_res.content
                            for pos in sign_positions:
                                packet = BytesIO()
                                page_width = current_page.mediabox.width
                                page_height = current_page.mediabox.height
                                c = canvas.Canvas(packet, pagesize=(page_width, page_height))
                                # 将印章图片放置在指定的位置
                                image = ImageReader(BytesIO(seal_file_content))
                                img_width, img_height = image.getSize()
                                seal_x = pos["x_axis"] * cm
                                seal_y = pos["y_axis"] * cm
                                width = pos["size"] * cm
                                height = (img_height / img_width) * width
                                c.drawImage(image, seal_x, seal_y, width, height,mask='auto')
                                c.save()
                                packet.seek(0)
                                seal_pdf = PdfReader(packet)
                                seal_page = seal_pdf.pages[0]
                                current_page.merge_page(seal_page)
                for page in pdf_reader.pages:
                    pdf_writer.add_page(page)
                output_buffer = BytesIO()
                pdf_writer.write(output_buffer)
                output_buffer.seek(0)
                object_key = f"{company_name}/{form_inst_id}/output_with_seals.pdf"
                bucket.put_object(object_key,output_buffer)
                url = bucket.sign_url("GET",object_key,3600)
                yida_client.update_form_data_by_id(form_uuid, yida_client.admin_user_id, form_inst_id, {
                        attachement_component_id: [{
                            "downloadUrl": url,
                            "name": atta.get("name"),
                            "previewUrl": url,
                            "url": url,
                            "ext": "pdf"
                        }]
                    })
                return ApiResponse.success(url)



@csrf_exempt
@require_http_methods(["POST"])
def calc_xm_cost(request,company_name):
    req_data = json.loads(request.body)
    detection_project_id = req_data.get('detection_project_id')
    cost_items = req_data.get('cost_items')
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.calc_cost({
        "cost_items":cost_items,
        "detection_project_id":detection_project_id
    })
    if(result.get("code")==200):
        return ApiResponse.success(data=result.get("data"))
    else:
        return ApiResponse.fail(message=result.get("message"))
    
def get_detection_config(request,company_name):
    detection_project_id = request.GET.get("detection_project_id")
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.get_extra_params(detection_project_id)
    if result.get("code") == 200:
        return ApiResponse.success(data=result.get("data"))
    else:
        return ApiResponse.fail(message=result.get("message"))
    

@csrf_exempt
@require_http_methods(["POST"])
def start_cutout_task(request,company_name):
    req_data = json.loads(request.body)
    task_info = {
              "supervise_no":req_data.get("supervise_no"),
              "start_time":req_data.get("start_time"),
              "end_time":req_data.get("end_time"),
              "remark": req_data.get("remark"),
              "mac_num":req_data.get("mac_num")
            }
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.create_cutout_task(task_info)
    if result.get("code") == 200:
        return ApiResponse.success(data=result.get("data"))
    else:
        return ApiResponse.fail(message=result.get("message"))
    

@csrf_exempt
@require_http_methods(["POST"])
def fake_sign(request,company_name):
    '''xm云平台伪签署'''
    req_data = json.loads(request.body)
    form_uuid = req_data.get("form_uuid")
    pdf_key = req_data.get("pdf_key")
    form_inst_id = req_data.get("form_inst_id")
    model_id = req_data.get("model_id")
    if form_inst_id:
        threading.Thread(target=xm_fake_sign,args=(company_name,form_uuid,pdf_key,form_inst_id,model_id)).start()
        return ApiResponse.success("已成功发起伪签署任务")
    else:
        return ApiResponse.fail("未找到表单记录")
    

    